package Tpackage;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Ticket {
    private int tickets = 10; // 初始化10张票
    private boolean isSoldOut = false; // 标志变量，表示票是否已经售罄
    private final Lock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();

    public void sellTicket() {
        lock.lock();
        try {
            while (tickets > 0) {
                try {
                    Thread.sleep(10); // 模拟售票过程中的延迟
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "---卖出的票" + tickets);
                tickets--;
                condition.signalAll(); // 唤醒所有等待的线程
                condition.await(); // 当前线程等待
            }
            if (!isSoldOut) {
                System.out.println(Thread.currentThread().getName() + "---票已售罄");
                isSoldOut = true; // 设置标志变量，避免重复打印
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public int getTickets() {
        return tickets;
    }
}
